# _*_ coding:utf-8 _*_

import re
import urllib2
from bs4 import BeautifulSoup
import json


# import format
# from format import save_json_text, load_json_text

class GetKillTrend(object):

    def __init__(self):
        self.urls = []
        self.urls.append(
            ['http://www.okooo.com/ajax/shahao/SSQ/100/EN/', 'http://www.okooo.com/ajax/shahao/SSQ/100/FN/'])
        self.urls.append(['http://trend.baidu.lecai.com/ssq/blueKillTrend.action?recentPhase=100',
                          'http://trend.baidu.lecai.com/ssq/redKillTrend.action?recentPhase=100'])
        self.urls.append(
            ['http://zx.caipiao.163.com/shahao/ssq/blue_100.html', 'http://zx.caipiao.163.com/shahao/ssq/red_100.html'])
        self.items = []
        # self.pipelines(self.items)

    def get(self, num):
        self.items = self.spider(self.urls, num)
        return self.items


    def spider(self, urls, num):
        item = []
        import sys
        default_encoding = 'utf-8'
        if sys.getdefaultencoding() != default_encoding:
            reload(sys)
            sys.setdefaultencoding(default_encoding)
        try:
            for url in urls:
                for u in url:
                    if 'SSQ/100/EN' in u:
                        enContent = json.loads(self.getResponseContent(u))
                        ss = ''
                        # print enContent[num]['KillNum']
                        sblue = enContent[num]['KillNum']
                        for killnum in sblue:
                            ss = ss + str(sblue[killnum]['Num']) + ','

                        ss = ss[:-1]
                        ss = 'ok,blue,' + str(num) + ',' + ss
                        item.append(ss)
                        # print u'澳客蓝球杀号：',
                        # print item[item.__len__() - 1]
                        # pass
                    elif 'SSQ/100/FN' in u:
                        fnContent = json.loads(self.getResponseContent(u))
                        ss = ''
                        # print fnContent[num]['KillNum']
                        sred = fnContent[num]['KillNum']
                        for killnum in sred:
                            ss = ss + str(sred[killnum]['Num']) + ','

                        ss = ss[:-1]
                        ss = 'ok,red,' + str(num) + ',' + ss
                        item.append(ss)
                        # print u'澳客红球杀号：',
                        # print item[item.__len__() - 1]
                        # pass
                    elif 'ssq/blue_100.html' in u:
                        htmlContent = self.getResponseContent(u)
                        soup = BeautifulSoup(htmlContent, 'lxml')
                        tags = soup.find_all('tr', attrs={'current'})
                        blue = tags[0].text
                        blue = blue.replace('\n', ',')
                        blue = blue.replace('--', '')
                        blue = blue.replace(('\xc2\xa0'), '')
                        blue = blue.replace('当前杀号,', '')
                        blue = blue[:-2]
                        blue = 'wy,blue' + blue
                        item.append(blue)
                        # print u'网易蓝球杀号：',
                        # print item[item.__len__() - 1]
                        # pass
                    elif 'ssq/red_100.html' in u:
                        htmlContent = self.getResponseContent(u)
                        soup = BeautifulSoup(htmlContent, 'lxml')
                        tags = soup.find_all('tr', attrs={'current'})
                        red = tags[0].text
                        red = red.replace('\n', ',')
                        red = red.replace('--', '')
                        red = red.replace(str('\xc2\xa0'), '')
                        red = red.replace('当前杀号,', '')
                        red = red[:-2]
                        red = 'wy,red' + red
                        item.append(red)
                        # print u'网易红球杀号：',
                        # print item[item.__len__() - 1]
                        # pass
                    elif 'blueKillTrend' in u:
                        htmlContent = self.getResponseContent(u)
                        soup = BeautifulSoup(htmlContent, 'lxml')
                        tags = soup.find_all('tr', attrs={})
                        blue = tags[100].text.replace('\n\n', '\n')
                        blue = blue.replace('当前期杀号', num)
                        blue = blue.replace('\n', ',')
                        blue = blue[:-2]
                        blue = 'bd,blue' + blue
                        item.append(blue)
                        # print u'百度彩蓝球杀号：',
                        # print item[item.__len__() - 1]
                        # pass
                    elif 'redKillTrend' in u:
                        htmlContent = self.getResponseContent(u)
                        soup = BeautifulSoup(htmlContent, 'lxml')
                        tags = soup.find_all('tr', attrs={})
                        red = tags[100].text.replace('\n\n', '\n')
                        red = red.replace('当前期杀号', num)
                        red = red.replace('\n', ',')
                        red = red[:-2]
                        red = 'bd,red' + red
                        item.append(red)
                        # print u'百度彩票红球杀号：',
                        # print item[item.__len__() - 1]
                        # pass
                    else:
                        pass
        except Exception, e:
            print e

        return item


    # 输出
    def pipelines(self, items):
        fileName = u'双色球杀号方案.txt'.encode('utf8')
        with open(fileName, 'w') as fp:
            for item in items:
                fp.write(
                    '%s  %s  \t  %s  %s  %s  %s  %s  %s  %s  \t %s  \t  %s  %s \n' % (
                        item.date.encode('utf8'), item.order.encode('utf8'), item.red1.encode('utf8'),
                        item.red2.encode('utf8'), item.red3.encode('utf8'), item.red4.encode('utf8'),
                        item.red5.encode('utf8'), item.red6.encode('utf8'), item.blue.encode('utf8'),
                        item.money.encode('utf8'), item.firstPrize.encode('utf8'), item.secondPrize.encode('utf8')))
                # self.log.info(u'日期为<<%s>>的数据输出成功' % item.date)


    # 获取url内容
    def getResponseContent(self, url):
        try:
            response = urllib2.urlopen(url.encode("utf8"))
        except:
            self.log.error(u'Python 返回URL:%s 数据失败' % url)
        else:
            # self.log.info(u'Python 返回URL:%s 数据成功' % url)
            return response.read()


if __name__ == '__main__':
    pass
